<template>
  <div>
    <el-row :gutter="32">
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="chart-wrapper">
          <div ref="chart" :style="{ width: width, height: height }"></div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="12">
        <div class="chart-wrapper">
          <div ref="ylchart" :style="{ width: width, height: height }"></div>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  import * as echarts from 'echarts';
  import moment from 'moment';
  import { CollectDataQuery,CollectDataQueryNew } from '@/api/system/datamanage';
  import resize from './mixins/resize';

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '350px'
      },
      autoResize: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        ylchart: null,
        ylTimes: [], // 保存时间
        ylValuesOne: [], // 保存对应时间的数据
        ylValuesTwo: [],

        chart: null,
        njTimes: [], // 保存时间
        njValues: [], // 保存对应时间的数据
        intervalIds: null, // 定时器ID
        isInitialized: false, // 是否已经找到匹配数据
        form: {
          startTime: '',
          endTime: '',
          sectionNo: '',
          pageSize: 1,
          pageNum: 1
        }
      };
    },
    mounted() {
      this.isInitialized = false
      this.initChart();
      this.initYlChart();
      this.initializeData();

    },
    activated() {
      this.isInitialized = false
      this.initChart();
      this.initYlChart();

    },
    deactivated() {
      if (this.chart) {
        this.chart.dispose();
      }
      if(this.ylchart){
        this.ylchart.dispose();
      }
      clearInterval(this.intervalIds); // 清除定时器
      this.intervalIds = null
      this.isInitialized = true
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$refs.chart);
        const option = {
          title: {
            text: '扭矩值'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.njTimes
          },
          yAxis: {
            type: 'value'
          },
          graphic: {
            type: 'text',     // 类型：文本
            left: 'center',
            top: 'middle',
            silent: true,     // 不响应事件
            invisible: this.njValues.length > 0,   // 有数据就隐藏
            style: {
              fill: '#9d9d9d',
              fontWeight: 'bold',
              text: '暂无数据',
              fontFamily: 'Microsoft YaHei',
              fontSize: '25px'
            }
          },
          series: [{
            name: '数据',
            type: 'line',
            data: this.njValues
          }]
        };
        this.chart.setOption(option);
      },
      async initializeData() {
        while (!this.isInitialized) {
          console.log("循环里面的状态：" + this.isInitialized);

          try {
            const currentTime = new Date(); // 当前时间
            this.form.startTime = this.parseTime(currentTime.getTime() - 10*60*1000); // 当前时间 前十分钟的数据
            this.form.endTime = this.parseTime(currentTime.getTime() + 10*1000); // 当前时间加一秒
            console.log('获取时间', this.form)
            const res = await CollectDataQueryNew(this.form);
            if (res.data != null) {
              const response = res.data
              const { currentMaximumMoment, maximumWorkingMoment1, maximumWorkingMoment2,time } = response;
              // 将UTC时间转换为本地时间并格式化
              const formattedTime = this.parseTime(currentTime).slice(11, 19);
              console.log("后端返回时间：" + formattedTime)
              console.log(this.parseTime(currentTime, '{h}:{i}:{s}'))
              console.log(this.form.startTime.slice(11, 19))
              console.log(this.form.endTime.slice(11, 19))

              if (formattedTime == this.parseTime(currentTime, '{h}:{i}:{s}') || formattedTime == this.form.startTime.slice(11, 19) || formattedTime == this.form.endTime.slice(11, 19)) {
                // 找到匹配的数据
                this.isInitialized = true;
                // this.njTimes.push(formattedTime);
                // this.njValues.push(currentMaximumMoment);
                // this.ylTimes.push(formattedTime);
                // this.ylValuesOne.push(maximumWorkingMoment1);
                // this.ylValuesTwo.push(maximumWorkingMoment2);
                this.njTimes = time.length<=0?[this.form.startTime.slice(11, 19),this.form.endTime.slice(11, 19)]:time
                this.ylTimes = time.length<=0?[this.form.startTime.slice(11, 19),this.form.endTime.slice(11, 19)]:time
                this.njValues = currentMaximumMoment.length<=0?['0','0']:currentMaximumMoment
                this.ylValuesOne = maximumWorkingMoment1.length<=0?['0','0']:maximumWorkingMoment1
                this.ylValuesTwo = maximumWorkingMoment2.length<=0?['0','0']:maximumWorkingMoment2
                // 更新扭矩图表
                this.chart.setOption({
                  xAxis: {
                    data: this.njTimes
                  },
                  graphic: {
                    invisible: this.njValues.length > 0,   // 有数据就隐藏
                  },
                  series: [{
                    data: this.njValues
                  }]
                });

                // 更新压力图表
                this.ylchart.setOption({
                  xAxis: {
                    data: this.ylTimes
                  },
                  graphic: {
                    invisible: this.ylValuesOne.length > 0 || this.ylValuesTwo.length > 0,   // 有数据就隐藏
                  },
                  series: [
                    {
                      name: '压力值1',
                      type: 'line',
                      data: this.ylValuesOne
                    },
                    {
                      name: '压力值2',
                      type: 'line',
                      data: this.ylValuesTwo
                    }
                  ]
                });

                // 开始定时请求
                this.startInterval();
              }
              // }
            }


          } catch (error) {
            console.error('Error fetching data:', error);
          }

          // 等待一段时间后再次尝试
          // await new Promise(resolve => setTimeout(resolve, 1000));
        }
      },
      async updateData() {
        try {
          const currentTime = new Date(); // 当前时间
          console.log('当前时间',currentTime)
          this.form.startTime = this.parseTime(currentTime.getTime() - 60000); // 当前时间减一秒
          this.form.endTime = this.parseTime(currentTime.getTime() + 1000); // 当前时间加一秒
          const response = await CollectDataQueryNew(this.form);
          console.log(9999,response)
          if (response.data != null) {
            const { currentMaximumMoment, maximumWorkingMoment1, maximumWorkingMoment2,time } = response.data;
            // 将UTC时间转换为本地时间并格式化
            const formattedTime = this.parseTime(currentTime).slice(11, 19);
            console.log(this.form.startTime.slice(11, 19))
            console.log(this.form.endTime.slice(11, 19))
            // 如果数组已满，移除最早的一个时间数据
            // if (this.njTimes.length >= 5) {
            //   this.njTimes.shift();
            //   this.njValues.shift();
            //   this.ylTimes.shift();
            //   this.ylValuesOne.shift();
            //   this.ylValuesTwo.shift();
            // }

            // 添加新的时间和数据
            // this.njTimes.push(formattedTime);
            // this.njValues.push(currentMaximumMoment);
            // this.ylTimes.push(formattedTime);
            // this.ylValuesOne.push(maximumWorkingMoment1);
            // this.ylValuesTwo.push(maximumWorkingMoment2);
                this.njTimes = time.length<=0?[this.form.startTime.slice(11, 19),this.form.endTime.slice(11, 19)]:time
                this.ylTimes = time.length<=0?[this.form.startTime.slice(11, 19),this.form.endTime.slice(11, 19)]:time
                this.njValues = currentMaximumMoment.length<=0?['0','0']:currentMaximumMoment
                this.ylValuesOne = maximumWorkingMoment1.length<=0?['0','0']:maximumWorkingMoment1
                this.ylValuesTwo = maximumWorkingMoment2.length<=0?['0','0']:maximumWorkingMoment2

            // 更新扭矩图表
            this.chart.setOption({
              xAxis: {
                data: this.njTimes
              },
              series: [{
                data: this.njValues
              }]
            });

            // 更新压力图表
            this.ylchart.setOption({
              xAxis: {
                data: this.ylTimes
              },
              series: [
                {
                  name: '压力值1',
                  type: 'line',
                  data: this.ylValuesOne
                },
                {
                  name: '压力值2',
                  type: 'line',
                  data: this.ylValuesTwo
                }
              ]
            });
          }

        } catch (error) {
          console.error('Error fetching data:', error);
        }
      },
      startInterval() {
        this.intervalIds = setInterval(this.updateData, 30 * 1000); // 每3秒更新一次
      },


      initYlChart() {
        this.ylchart = echarts.init(this.$refs.ylchart);
        const option = {
          title: {
            text: '压力值'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.ylTimes
          },
          yAxis: {
            type: 'value'
          },
          graphic: {
            type: 'text',     // 类型：文本
            left: 'center',
            top: 'middle',
            silent: true,     // 不响应事件
            invisible: this.ylValuesOne.length > 0 || this.ylValuesTwo.length > 0,   // 有数据就隐藏
            style: {
              fill: '#9d9d9d',
              fontWeight: 'bold',
              text: '暂无数据',
              fontFamily: 'Microsoft YaHei',
              fontSize: '25px'
            }
          },
          series: [
            {
              name: '压力值1',
              type: 'line',
              data: this.ylValuesOne
            },
            {
              name: '压力值2',
              type: 'line',
              data: this.ylValuesTwo
            }
          ]
        };
        this.ylchart.setOption(option);
      },
    }
  };
</script>

<style scoped>
  /* 样式可以根据需要自定义 */
  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }

  @media (max-width:1024px) {
    .chart-wrapper {
      padding: 8px;
    }
  }
</style>
